package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.util.FastDFSClient;
import com.changgou.file.util.FastDFSFile;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/file")
public class FileController {


    /**
     * @Description:使用fastDFS进行文件的上传
     * @Author: 陈安
     * @Date: 12-04
     */
    @PostMapping("/update")
    public Result update(MultipartFile file) {
        try {
            //判断文件是否存在
            if (file == null) {
                throw new Exception("文件不存在");
            }
            //获取文件上传完整名称
            String originalFilename = file.getOriginalFilename();
            if (StringUtils.isEmpty(originalFilename)) {
                throw new Exception("文件不存在");
            }

            //获取文件的扩展名
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

            //获取文件的内容
            byte[] bytes = file.getBytes();

            //创建文件上传的封装的实体类
//            String originalFilename1 = file.getOriginalFilename();
//            byte[] bytes1 = file.getBytes();
//            String substring1 = originalFilename.substring(originalFilename.lastIndexOf("." + 1));
//            FastDFSFile fastDFSFile1 = new FastDFSFile(originalFilename, bytes, substring);
//            String[] upload1 = FastDFSClient.upload(fastDFSFile1);
//            String s1 = FastDFSClient.getTrackerUrl() + upload1[0] + "/" + upload1[1];
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename, bytes, substring);

            //给予工具类进行文件上传,并且接收返回的参数,String[]
            //这个string[]返回的两个参数是组名和路径名
            String[] upload = FastDFSClient.upload(fastDFSFile);

            //封装返回的结果
            String s = FastDFSClient.getTrackerUrl() + upload[0] + "/" + upload[1];
            return new Result(true,StatusCode.OK,"文件上传成功",s);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return new Result(true, StatusCode.ERROR, "文件上传失败了哦!");
    }
}
